package com.zhongjian.technologycal.mall.adapter;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.squareup.picasso.Picasso;
import com.zhongjian.technologycal.mall.R;
import com.zhongjian.technologycal.mall.activity.shoppingcart.bean.ProductListBean;
import com.zhongjian.technologycal.mall.base.BaseContacts;
import com.zhongjian.technologycal.mall.bean.CartBean;
import com.zhongjian.technologycal.mall.utils.UiUtils;

import java.util.ArrayList;

import me.drakeet.materialdialog.MaterialDialog;

/**
 * 购物车适配器
 * Created by wei on 2018/1/22.
 */

public class ShoppingCartAdapter extends BaseExpandableListAdapter {

    private Context mContext;
    private ShoppingCartAdapter.CheckInterface checkInterface;
    private ShoppingCartAdapter.ModifyCountInterface modifyCountInterface;
    private ArrayList<CartBean> cartList;
    private GroupEditorListener groupEditorListener;
    private MaterialDialog mMaterialDialog = null;

    public ShoppingCartAdapter(Context context, ArrayList<CartBean> cartList) {
        this.mContext = context;
        this.cartList = cartList;
    }

    @Override
    public int getGroupCount() {
        return cartList.size();
    }

    @Override
    public int getChildrenCount(int groupPosition) {
        return cartList.get(groupPosition).getProductList().size();
    }

    @Override
    public Object getGroup(int groupPosition) {
        return cartList.get(groupPosition);
    }

    @Override
    public Object getChild(int groupPosition, int childPosition) {
        return cartList.get(groupPosition).getProductList().get(childPosition);
    }

    @Override
    public long getGroupId(int groupPosition) {
        return groupPosition;
    }

    @Override
    public long getChildId(int groupPosition, int childPosition) {
        return childPosition;
    }

    @Override
    public boolean hasStableIds() {
        return false;
    }


    @Override
    public View getGroupView(final int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
        final ShoppingCartAdapter.GroupViewHolder groupViewHolder;
        if (convertView == null) {
            groupViewHolder = new GroupViewHolder();
            convertView =  UiUtils.inflate(R.layout.item_shopcat_group);
            groupViewHolder.storeCheckBox =convertView.findViewById(R.id.store_checkBox);
            groupViewHolder.storeName =  convertView.findViewById(R.id.store_name);
            groupViewHolder.storeEdit =  convertView.findViewById(R.id.store_edit);
            convertView.setTag(groupViewHolder);

        } else {
            groupViewHolder = (ShoppingCartAdapter.GroupViewHolder) convertView.getTag();
        }
        final CartBean group = cartList.get(groupPosition);
        if(group.getProducerName().equals("")){
            groupViewHolder.storeName.setText("无商家");
        }else{
            groupViewHolder.storeName.setText(group.getProducerName());
        }

        groupViewHolder.storeCheckBox.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                group.setChoose(((CheckBox) v).isChecked());
                checkInterface.checkGroup(groupPosition, ((CheckBox) v).isChecked());// 暴露组选接口
            }
        });
        groupViewHolder.storeCheckBox.setChecked(group.isChoose());


        /**
         * 思路:当我们按下组的"编辑"按钮后，组处于编辑状态，文字显示"完成"
         * 当我们点击“完成”按钮后，文字显示"编辑“,组处于未编辑状态
         */
        if (group.isEditor()) {
            groupViewHolder.storeEdit.setText("完成");
        } else {
            groupViewHolder.storeEdit.setText("编辑");
        }
        groupViewHolder.storeEdit.setOnClickListener(new GroupViewClick(groupPosition, groupViewHolder.storeEdit, group));
        notifyDataSetChanged();
        return convertView;
    }

    @Override
    public View getChildView(final int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
        final ShoppingCartAdapter.ChildViewHolder childViewHolder;
        if (convertView == null) {
            convertView =  UiUtils.inflate(R.layout.item_shopcat_product);
            childViewHolder = new ChildViewHolder();
            childViewHolder.singleCheckBox = convertView.findViewById(R.id.single_checkBox);
            childViewHolder.goodsImage = convertView.findViewById(R.id.goods_image);
            childViewHolder.goodsName = convertView.findViewById(R.id.goods_name);
            childViewHolder.goods_size = convertView.findViewById(R.id.goods_size);
            childViewHolder.goodsPrice = convertView.findViewById(R.id.goods_price);
            childViewHolder.goodsBuyNum = convertView.findViewById(R.id.goods_buyNum);
            childViewHolder.reduceGoodsNum = convertView.findViewById(R.id.reduce_goodsNum);
            childViewHolder.increaseGoodsNum = convertView.findViewById(R.id.increase_goods_Num);
            childViewHolder.goodsNum = convertView.findViewById(R.id.goods_Num);
            childViewHolder.goodsData = convertView.findViewById(R.id.goods_data);
            childViewHolder.goodsSize = convertView.findViewById(R.id.goodsSize);
            childViewHolder.delGoods = convertView.findViewById(R.id.del_goods);
            childViewHolder.editGoodsData = convertView.findViewById(R.id.edit_goods_data);
            convertView.setTag(childViewHolder);
        } else {
            childViewHolder = (ShoppingCartAdapter.ChildViewHolder) convertView.getTag();
        }

        final ProductListBean childInfo = cartList.get(groupPosition).getProductList().get(childPosition);
        if(childInfo != null){
            childViewHolder.goodsName.setText(""+ childInfo.getProduct().getProductname());
            Picasso.get().load(BaseContacts.BASE_URL+childInfo.getProduct()
                    .getProductphotos().get(0).getPhoto()).into(childViewHolder.goodsImage);
            childViewHolder.goods_size.setText("规格："+ childInfo.getProductSpec().getSpecname());
            childViewHolder.goodsPrice.setText("¥"+ childInfo.getProductSpec().getPrice());
            childViewHolder.goodsBuyNum.setText("x"+childInfo.getProductnum());
            childViewHolder.goodsNum.setText(""+ childInfo.getProductnum());

            /**
             * 根据组的编辑按钮的可见与不可见，去判断是组对下辖的子元素编辑  还是ActionBar对组的下瞎元素的编辑
             * 如果组的编辑按钮可见，那么肯定是组对自己下辖元素的编辑·
             */
            if (cartList.get(groupPosition).isEditor() ==  true) {
                childViewHolder.editGoodsData .setVisibility(View.VISIBLE);
                childViewHolder.goodsData .setVisibility(View.GONE);
            } else {
                childViewHolder.editGoodsData .setVisibility(View.GONE);
                childViewHolder.goodsData .setVisibility(View.VISIBLE);
            }

            childViewHolder.singleCheckBox.setChecked(childInfo.isChoosed());
            childViewHolder.singleCheckBox.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    childInfo.setChoosed(((CheckBox) v).isChecked());
                    childViewHolder.singleCheckBox.setChecked(((CheckBox) v).isChecked());
                    checkInterface.checkChild(groupPosition, childPosition, ((CheckBox) v).isChecked());// 暴露子选接口
                }
            });

            childViewHolder.increaseGoodsNum.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    modifyCountInterface.doIncrease(groupPosition, childPosition, childViewHolder.goodsNum, childViewHolder.singleCheckBox.isChecked());// 暴露增加接口
                }
            });
            childViewHolder.reduceGoodsNum.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    modifyCountInterface.doDecrease(groupPosition, childPosition, childViewHolder.goodsNum, childViewHolder.singleCheckBox.isChecked());// 暴露删减接口
                }
            });
            //删除
            childViewHolder.delGoods.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mMaterialDialog = new MaterialDialog(mContext)
                            .setMessage("您确定要移除购物车商品吗？")
                            .setPositiveButton("确定", new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    modifyCountInterface.childDelete(groupPosition, childPosition);
                                    mMaterialDialog.dismiss();
                                }
                            })
                            .setNegativeButton("取消", new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    mMaterialDialog.dismiss();
                                }
                            });
                    mMaterialDialog.setCanceledOnTouchOutside(true);
                    mMaterialDialog.show();

                }
            });

        }

        return convertView;
    }
    @Override
    public boolean isChildSelectable(int groupPosition, int childPosition) {
        return true;
    }

    public void setCheckInterface(ShoppingCartAdapter.CheckInterface checkInterface) {
        this.checkInterface = checkInterface;
    }

    public void setModifyCountInterface(ShoppingCartAdapter.ModifyCountInterface modifyCountInterface) {
        this.modifyCountInterface = modifyCountInterface;
    }

    /**
     * 复选框接口
     */
    public interface CheckInterface {
        /**
         * 组选框状态改变触发的事件
         *
         * @param groupPosition 组元素位置
         * @param isChecked     组元素选中与否
         */
        void checkGroup(int groupPosition, boolean isChecked);

        /**
         * 子选框状态改变时触发的事件
         *
         * @param groupPosition 组元素位置
         * @param childPosition 子元素位置
         * @param isChecked     子元素选中与否
         */
        void checkChild(int groupPosition, int childPosition, boolean isChecked);
    }

    /**
     * 改变数量的接口
     */
    public interface ModifyCountInterface {
        /**
         * 增加操作
         *
         * @param groupPosition 组元素位置
         * @param childPosition 子元素位置
         * @param showCountView 用于展示变化后数量的View
         * @param isChecked     子元素选中与否
         */
        void doIncrease(int groupPosition, int childPosition, View showCountView, boolean isChecked);

        /**
         * 删减操作
         *
         * @param groupPosition 组元素位置
         * @param childPosition 子元素位置
         * @param showCountView 用于展示变化后数量的View
         * @param isChecked     子元素选中与否
         */
        void doDecrease(int groupPosition, int childPosition, View showCountView, boolean isChecked);

        /**
         * 删除子item
         *
         * @param groupPosition
         * @param childPosition
         */
        void childDelete(int groupPosition, int childPosition);
    }

    public GroupEditorListener getGroupEditorListener() {
        return groupEditorListener;
    }

    public void setGroupEditorListener(GroupEditorListener groupEditorListener) {
        this.groupEditorListener = groupEditorListener;
    }

    /**
     * 监听编辑状态
     */
    public interface GroupEditorListener {
        void groupEditor(int groupPosition);
    }



    /**
     * 使某个组处于编辑状态
     * <p/>
     * groupPosition组的位置
     */
    class GroupViewClick implements View.OnClickListener {
        private int groupPosition;
        private TextView editor;
        private CartBean group;

        public GroupViewClick(int groupPosition, TextView editor, CartBean group) {
            this.groupPosition = groupPosition;
            this.editor = editor;
            this.group = group;
        }

        @Override
        public void onClick(View v) {
            int groupId = v.getId();
            if (groupId == editor.getId()) {
//                groupEditorListener.groupEditor(groupPosition);
                if (group.isEditor()) {
                    group.setEditor(false);
                } else {
                    group.setEditor(true);
                }
                notifyDataSetChanged();
            }
        }
    }

    /**
     * 父布局Holder
     */
    public class GroupViewHolder {
        CheckBox storeCheckBox;
        TextView storeName;
        TextView storeEdit;

    }

    /**
     * 子布局Holder
     */
    public class ChildViewHolder {
        CheckBox singleCheckBox;
        ImageView goodsImage;
        TextView goodsName;
        TextView goods_size;
        TextView goodsPrice;
        TextView goodsPrimePrice;
        TextView goodsBuyNum;
        RelativeLayout goodsData;
        TextView reduceGoodsNum;
        TextView goodsNum;
        TextView increaseGoodsNum;
        TextView goodsSize;
        TextView delGoods;
        LinearLayout editGoodsData;

    }
}
